package com.example.cangzhou.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cangzhou.entity.News;
import com.example.cangzhou.result.Result;
import com.example.cangzhou.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    /**
     * 新增新闻
     */
    @PostMapping( "/create")
    public Result<News> createNews(@RequestBody News news) {
        news.setCreateTime(LocalDateTime.now());
        news.setUpdateTime(LocalDateTime.now());
        newsService.save(news);
        return Result.success();
    }
    /**
     * 查询所有新闻
     */
    @GetMapping
    public Result<List<News>> getAllNews() {
        List<News> newsList = newsService.list();
        return Result.success(newsList);
    }

    /**
     * 根据ID查询新闻
     */
    @GetMapping("/{id}")
    public Result<News> getNewsById(@PathVariable Long id) {
        News news = newsService.getById(id);
        return Result.success(news);
    }



    /**
     * 更新新闻
     */
    @PutMapping("/{id}")
    public Result<Void> updateNews(@PathVariable Long id, @RequestBody News news) {
        if (!id.equals(news.getId())) {
            return Result.error("ID不匹配");
        }
        newsService.updateById(news);
        return Result.success();
    }

    /**
     * 删除新闻
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteNews(@PathVariable Long id) {
        newsService.removeById(id);
        return Result.success();
    }
    
    /**
     * 分页查询新闻
     */
    @GetMapping("/page")
    public Result<IPage<News>> getNewsByPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        IPage<News> newsPage = newsService.page(new Page<>(pageNum, pageSize), null);
        return Result.success(newsPage);
    }
//
//    /**
//     * 根据分类查询新闻
//     */
//    @GetMapping("/category/{category}")
//    public ResponseEntity<List<News>> getNewsByCategory(@PathVariable String category) {
//        List<News> newsList = newsService.getNewsByCategory(category);
//        return ResponseEntity.ok(newsList);
//    }
//
//    /**
//     * 根据状态查询新闻
//     */
//    @GetMapping("/status/{status}")
//    public ResponseEntity<List<News>> getNewsByStatus(@PathVariable String status) {
//        List<News> newsList = newsService.getNewsByStatus(status);
//        return ResponseEntity.ok(newsList);
//    }
}